package com.newsnetwork.api;

import com.newsnetwork.grace.result.CommonJSONResult;
import com.newsnetwork.pojo.vo.AppUserVO;
import com.newsnetwork.utils.JsonUtils;
import com.newsnetwork.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author: HuangDekai
 * @date: 2022/11/3 23:16
 * @version: 1.0
 * @since: jdk8
 */
public class BaseController {
    @Autowired
    public RedisOperator redisOperator;

    @Autowired
    public RestTemplate restTemplate;

    public static final String MOBILE_SMSCODE = "mobile:smscode";
    public static final String REDIS_USER_TOKEN = "redis_user_token";
    public static final String REDIS_USER_INFO = "redis_user_info";
    public static final String REDIS_ADMIN_TOKEN = "redis_admin_token";

    /**
     * 该标签用于查询 标签分类
     */
    public static final String REDIS_ALL_CATEGORY = "redis_all_category";

    /**
     * 用于查询用户的粉丝数和关注数
     */
    public static final String REDIS_WRITER_FANS_COUNTS = "redis_writer_fans_counts";
    public static final String REDIS_MY_FOLLOW_COUNTS = "redis_my_follow_counts";

    /**
     * 文章阅读数
     */
    public static final String REDIS_ARTICLE_READ_COUNTS = "redis_article_read_counts";
    public static final String REDIS_ALREADY_READ = "redis_already_read";
    /**
     * 文章评论书
     */
    public static final String REDIS_ARTICLE_COMMENT_COUNTS = "redis_article_comment_counts";
    /**
     * cookie 的域, 即 cookie 的作用范围
     */
    @Value("${website.domain-name}")
    public String COOKIE_DOMAIN;
    public static final Integer COOKIE_MONTH = 30 * 24 * 60 * 60;
    public static final Integer COOKIE_DELETED = 0;

    /**
     * 分页查询时, 默认从第 1 页开始
     */
    public static final Integer COMMON_START_PAGE = 1;
    /**
     * 分页查询时, 默认一页 10 条数据
     */
    public static final Integer COMMON_PAGE_SIZE = 10;

    /**
     * 获取 BO 中的错误信息
     * @param result 错误信息
     */
    public Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList) {
            String field = error.getField();
            String msg = error.getDefaultMessage();
            map.put(field, msg);
        }

        return map;
    }

    public void setCookie(HttpServletRequest request,
                          HttpServletResponse response,
                          String cookieName,
                          String cookieValue,
                          Integer maxAge) {
        try {
            cookieValue = URLEncoder.encode(cookieValue, "UTF-8");
            setCookieValue(request, response, cookieName, cookieValue, maxAge);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public void setCookieValue(HttpServletRequest request,
                          HttpServletResponse response,
                          String cookieName,
                          String cookieValue,
                          Integer maxAge) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setMaxAge(maxAge);
        cookie.setDomain(COOKIE_DOMAIN);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public Integer getCountsFromRedis(String key) {
        String countsStr = redisOperator.get(key);
        if (StringUtils.isBlank(countsStr)) {
            return null;
        }
        return Integer.valueOf(countsStr);
    }

    /**
     * 发起远程调用，获得用户的基本信息
     * @param idSet 发布者列表
     * @return
     */
    protected List<AppUserVO> getBasicUserList(Set idSet) {
        String serviceId = "SERVICE-USER";
        String userServiceUrlExecute = "http://"+ serviceId +"/user/queryByIds?userIds=" + JsonUtils.objectToJson(idSet);
        ResponseEntity<CommonJSONResult> responseEntity = restTemplate.getForEntity(userServiceUrlExecute, CommonJSONResult.class);
        CommonJSONResult bodyResult = responseEntity.getBody();
        List<AppUserVO> userVOList = null;
        if (bodyResult.getStatus() == 200) {
            String userJson = JsonUtils.objectToJson(bodyResult.getData());
            userVOList = JsonUtils.jsonToList(userJson, AppUserVO.class);
        }
        return userVOList;
    }
}
